import 'dart:async';
import 'dart:collection';
import 'dart:ffi';

import 'package:bruno/bruno.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/tree_mode.dart';
import 'package:yt_devops/components/yt_multi_column_picker/model/yt_multi_column_model.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/extensions.dart';

class SelectProductTypePageController extends GetxController {
  DeviceServices services = Get.find<DeviceServices>();

  Map<String, dynamic>? selectedEntity;

  Key brnMultiColumnPickerKey = UniqueKey();

  int firstIndex = 0;

  MultiColumnModel? tree;

  List<int> selectedIndexes = [];

  @override
  void onInit() {
    selectedEntity = Get.arguments;

    getDeviceType();

    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  Future getDeviceType() async =>
      await Configs.httpClient.requestWithLoading(() async {
        var data = await services.getProductTypelist();

        List<MultiColumnModel> treeList = data
            .map<MultiColumnModel>((e) => MultiColumnModel(
                  e['id'],
                  title: e['name'],
                  selectable: true,
                  pickerType: MultiColumnPickerType.unLimit,
                  selectList: (e['children'] ?? [])
                      .map<MultiColumnModel>((p) => MultiColumnModel(
                            p['id'],
                            selectable: true,
                            pickerType: MultiColumnPickerType.radio,
                            title: p['name'],
                          ))
                      .toList()
                    ..insert(
                      0,
                      MultiColumnModel(
                        e['id'],
                        selectable: true,
                        pickerType: MultiColumnPickerType.unLimit,
                        title: ResKey.all.tr,
                      ),
                    ),
                ))
            .toList();

        tree = MultiColumnModel(
          '',
          title: '',
          pickerType: MultiColumnPickerType.unLimit,
          selectList: treeList,
        );

        setDefaultSelectedIndexes(treeList);

        // var treeList = data
        //     .map<MultiColumnModel>((e) => MultiColumnModel(
        //           e['id'],
        //           title: e['name'],
        //           pickerType: MultiColumnPickerType.unLimit,
        //           subNodes: e['children']
        //               .map<MultiColumnModel>((p) => MultiColumnModel(p['id'],
        //                   title: p['name'],
        //                   pickerType: MultiColumnPickerType.unLimit,
        //                   selectList: e['children']
        //                       .map<MultiColumnModel>((p) => MultiColumnModel(
        //                             '${e['id']}-${p['id']}',
        //                             pickerType: MultiColumnPickerType.radio,
        //                             title: p['name'],
        //                           ))
        //                       .toList()))
        //               .toList(),
        //         ))
        //     .toList();

        // List<BrnPickerEntity> entitys = data
        //     .map<BrnPickerEntity>((e) => BrnPickerEntity(
        //           maxSelectedCount: 1,
        //           name: e['name'],
        //           value: e['id'].toString(),
        //           isSelected: selectedEntity?['id'] == e['id'],
        //           children: e['children']
        //               .map<BrnPickerEntity>((p) => BrnPickerEntity(
        //                   type: 'radio',
        //                   name: p['name'],
        //                   value: p['id'].toString(),
        //                   isSelected:
        //                       selectedEntity?['subProduct']?['id'] == p['id']))
        //               .toList()
        //             ..insert(
        //                 0,
        //                 BrnPickerEntity(
        //                     maxSelectedCount: 1,
        //                     type: 'unlimit',
        //                     name: ResKey.all.tr,
        //                     value: null,
        //                     isSelected: selectedEntity != null &&
        //                         selectedEntity?['subProduct'] == null)),
        //         ))
        //     .toList();

        // entity = BrnPickerEntity(children: entitys, maxSelectedCount: 1);

        update();
      }, showLoading: true);

  setDefaultSelectedIndexes(List<MultiColumnModel> list) {
    if (list.isNotEmpty) {
      selectedEntity ??= {
        'id': list.first.value,
        'name': list.first.title,
      };
    }
    selectedIndexes.clear();
    for (var i = 0; i < list.length; i++) {
      var parent = list[i];
      if (selectedEntity?['id'] == parent.value) {
        selectedIndexes.add(i);
        firstIndex = i;
        for (var j = 0; j < parent.selectList.length; j++) {
          var child = parent.selectList[j];
          if (selectedEntity?['subProduct']?['id'] == child.value) {
            selectedIndexes.add(j);
          }
        }
        // 第二列没有选中那就默认第一个
        if (selectedIndexes.length == 1) {
          selectedIndexes.add(0);
        }

        break;
      }
    }
  }

  onEntityTap(int column, int row, MultiColumnModel model) {
    if (column == 0) {
      firstIndex = row;
    } else {
      selectedEntity = {
        'id': tree!.selectList[firstIndex].value,
        'name': tree!.selectList[firstIndex].title,
        'subProduct': model.value == tree!.selectList[firstIndex].value
            ? null
            : {'id': model.value, 'name': model.title}
      };
    }
  }

  reset() {
    //强制重新渲染
    brnMultiColumnPickerKey = UniqueKey();
    selectedEntity = null;
    setDefaultSelectedIndexes(tree?.selectList ?? []);
    update();
  }
}
